<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="query.name" size="medium" class="filter-item w-200" placeholder="角色名称"/>
            <el-select class="filter-item w-200" size="medium" clearable  v-model="query.school_id" placeholder="请选择学校">
                <el-option v-for="item in schools" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
            <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchList(resetPage = true)">搜索</el-button>
            <el-button class="filter-item" type="primary" size="medium" style="float: right" icon="el-icon-plus" @click="showAdd" v-permission="'user-roles.store'">新 增</el-button>
        </div>
        <el-table :data="lists" border stripe v-loading="visible.listLoading">
            <el-table-column label="#" align="center" width="50px">
                <template slot-scope="scope">
                    {{query.size * (query.page-1) + scope.$index + 1}}
                </template>
            </el-table-column>
            <el-table-column label="名称" prop="name" align="center">
            </el-table-column>
            <el-table-column label="学校" prop="school.name" align="center">
            </el-table-column>
            <el-table-column label="是否默认角色" prop="is_default" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-check" v-if="scope.row.is_default === 1" />
                    <i class="el-icon-close" v-else />
                </template>
            </el-table-column>
            <el-table-column label="是否能订早餐" prop="can_breakfast" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-check" v-if="scope.row.can_breakfast === 1" />
                    <i class="el-icon-close" v-else />
                </template>
            </el-table-column>
            <el-table-column label="早餐付款比例" prop="breakfast_rate" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.morning_price_rule === 2 ? scope.row.breakfast_rate : '' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否能订午餐" prop="can_lunch" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-check" v-if="scope.row.can_lunch === 1" />
                    <i class="el-icon-close" v-else />
                </template>
            </el-table-column>
            <el-table-column label="午餐付款比例" prop="lunch_rate" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.lunch_price_rule === 2 ? scope.row.lunch_rate : '' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否能订晚餐" prop="can_dinner" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-check" v-if="scope.row.can_dinner === 1" />
                    <i class="el-icon-close" v-else />
                </template>
            </el-table-column>
            <el-table-column label="晚餐付款比例" prop="dinner_rate" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.dinner_price_rule === 2 ? scope.row.dinner_rate : '' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="created_at" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center" width="150px">
                <template slot-scope="scope">
                    <el-button class="filter-item" type="primary" size="mini" @click="showEdit(scope.row)" icon="el-icon-edit" v-permission="'user-roles.update'">编 辑</el-button>
                    <!--<el-button class="filter-item" type="danger" size="mini" @click="showChange(scope.row)" v-permission="'user-roles.update'" v-if="scope.row.is_default === 0">默认角色</el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="query.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="query.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="formTitle" width="1000px" :visible.sync="visible.form" @close="$refs['form'].resetFields()">
            <el-form :model="form" ref="form" label-width="140px" :rules="ruleFloat">
                <el-form-item label="名称" prop="name" verify required>
                    <el-input v-model="form.name" placeholder="请输入角色名称"/>
                </el-form-item>
                <el-form-item label="学校" prop="school_id" verify required>
                    <el-select style="width: 100%;" v-model="form.school_id" placeholder="请选择学校">
                        <el-option v-for="item in schools" :key="item.id" :value="item.id" :label="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="说明" prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入说明"/>
                </el-form-item>
                <el-row type="flex" class="row-bg" justify="space-between">
                    <el-col :span="6">
                        <el-form-item label="是否能订早餐" prop="can_breakfast" verify required>
                            <el-switch v-model="form.can_breakfast" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"></el-switch>
                        </el-form-item>
                        <el-form-item label="早餐价格规则" prop="morning_price_rule" verify required>
                            <el-select class="form-select" v-model="form.morning_price_rule" placeholder="请选择规则">
                                <el-option v-for="rule in priceRoles" :key="rule.index" :value="rule.index" :label="rule.label"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="form.morning_price_rule === 1" label="早餐价格" prop="morning_price" required>
                            <el-input-number v-model="form.morning_price" :min="0" placeholder="请输入价格" class="price"/>
                        </el-form-item>
                        <el-form-item v-if="form.morning_price_rule === 2" label="早餐付款比例" prop="breakfast_rate" required>
                            <el-input-number v-model="form.breakfast_rate" :min="0" type="number" placeholder="请输入比例" class="price"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="是否能订午餐" prop="can_lunch" verify required>
                            <el-switch v-model="form.can_lunch" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"></el-switch>
                        </el-form-item>
                        <el-form-item label="午餐价格规则" prop="lunch_price_rule" verify required>
                            <el-select class="form-select" v-model="form.lunch_price_rule" placeholder="请选择规则">
                                <el-option v-for="rule in priceRoles" :key="rule.index" :value="rule.index" :label="rule.label"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="form.lunch_price_rule === 1" label="午餐价格" prop="lunch_price" required>
                            <el-input-number v-model="form.lunch_price" :min="0" placeholder="请输入价格" class="price"/>
                        </el-form-item>
                        <el-form-item v-if="form.lunch_price_rule === 2" label="午餐付款比例" prop="lunch_rate"  required>
                            <el-input-number v-model="form.lunch_rate" :min="0" type="number" placeholder="请输入比例" class="price"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="是否能订晚餐" prop="can_dinner" verify required>
                            <el-switch v-model="form.can_dinner" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"></el-switch>
                        </el-form-item>
                        <el-form-item label="晚餐价格规则" prop="dinner_price_rule" verify required>
                            <el-select class="form-select" v-model="form.dinner_price_rule" placeholder="请选择规则">
                                <el-option v-for="rule in priceRoles" :key="rule.index" :value="rule.index" :label="rule.label"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="form.dinner_price_rule === 1" label="晚餐价格" prop="dinner_price" required>
                            <el-input-number v-model="form.dinner_price" :min="0" placeholder="请输入价格" class="price"/>
                        </el-form-item>
                        <el-form-item v-if="form.dinner_price_rule === 2" label="晚餐付款比例" prop="dinner_rate" required>
                            <el-input-number v-model="form.dinner_rate" :min="0" type="number" placeholder="请输入比例" class="price"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="visible.form=false">取消</el-button>
                <el-button type="primary" @click="handleForm" :loading="visible.formLoading">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  import { fetchRoles, addRoles, editRoles, changeRoles } from '@/api/user'
  import { isRicePriceAvailable, isPercentAvailable } from '@/utils/validate'
  import { fetchData } from '@/api/data'
  export default {
    name: 'user-role',
    data() {
      const validateFloat = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入比例'))
        } else if (!isPercentAvailable(value)) {
          callback(new Error('请输入正确百分比'))
        }
        callback()
      }
      const validateMorningPrice = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入早餐价格'))
        } else {
          if (!isRicePriceAvailable(value)) {
            callback(new Error('早餐价格格式错误'))
          }
          callback()
        }
      }
      const validateLunchPrice = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入午餐价格'))
        } else {
          if (!isRicePriceAvailable(value)) {
            callback(new Error('午餐价格格式错误'))
          }
          callback()
        }
      }
      const validateDinnerPrice = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入晚餐价格'))
        } else {
          if (!isRicePriceAvailable(value)) {
            callback(new Error('晚餐价格格式错误'))
          }
          callback()
        }
      }
      return {
        ruleFloat: {
          dinner_rate: [
            { validator: validateFloat, trigger: ['change', 'blur'] }
          ],
          lunch_rate: [
            { validator: validateFloat, trigger: ['change', 'blur'] }
          ],
          breakfast_rate: [
            { validator: validateFloat, trigger: ['change', 'blur'] }
          ],
          morning_price: [
            { validator: validateMorningPrice, trigger: ['blur', 'change'] }
          ],
          lunch_price: [
            { validator: validateLunchPrice, trigger: ['blur', 'change'] }
          ],
          dinner_price: [
            { validator: validateDinnerPrice, trigger: ['blur', 'change'] }
          ]
        },
        query: {
          name: null,
          school_id: null,
          size: 10,
          page: 1
        },
        visible: {
          listLoading: false,
          formLoading: false,
          form: false
        },
        form: {
          name: '',
          is_default: 0,
          description: '',
          school_id: '',
          can_breakfast: 1,
          can_lunch: 1,
          can_dinner: 1,
          breakfast_rate: 100.00,
          lunch_rate: 100.00,
          dinner_rate: 100.00,
          morning_price_rule: 2,
          morning_price: '',
          lunch_price_rule: 2,
          lunch_price: '',
          dinner_price_rule: 2,
          dinner_price: ''
        },
        lists: [],
        schools: [],
        total: 0,
        formTitle: '',
        formType: '',
        editRow: '',
        priceRoles: [
          {
            index: 1,
            label: '固定餐标'
          },
          {
            index: 2,
            label: '计费餐标'
          }
        ]
      }
    },
    methods: {
      handleSizeChange(size) {
        this.query.size = size
        this.fetchList()
      },
      handleCurrentChange(page) {
        this.query.page = page
        this.fetchList()
      },
      fetchList(resetPage = false) {
        if (resetPage === true) {
          this.query.page = 1
        }
        this.visible.listLoading = true
        fetchRoles(this.query).then(res => {
          this.lists = res.data
          this.total = res.meta.total
          this.visible.listLoading = false
        })
      },
      showAdd() {
        this.resetForm('form')
        Object.assign(this.form, this.$options.data().form)
        this.formType = 'add'
        this.formTitle = '新增用户角色'
        this.visible.form = true
      },
      showEdit(row) {
        Object.existAssign(this.form, row)
        this.editRow = row
        this.formType = 'edit'
        this.formTitle = '编辑用户角色'
        this.visible.form = true
      },
      handleForm() {
        this.$refs.form.validate().then(valid => {
          if (valid) {
            this.visible.formLoading = true
            if (this.formType === 'add') {
              addRoles(this.form).then(res => {
                this.fetchList()
                this.visible.form = false
                this.$message.success('新增成功')
                this.visible.formLoading = false
              }).catch(err => {
                this.visible.formLoading = false
                this.$handleNotFound(err)
              })
            } else {
              editRoles(this.form, this.editRow.id).then(res => {
                this.fetchList()
                this.visible.form = false
                this.$message.success('编辑成功')
                this.visible.formLoading = false
              }).catch(err => {
                this.$handleNotFound(err, '用户角色不存在')
                this.visible.formLoading = false
              })
            }
          }
        }).catch(() => {})
      },
      showChange(row) {
        this.$confirm('是否设置为默认角色', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          changeRoles(row.id).then(res => {
            if (res.result === 'failed') {
              this.$message.error(res.msg)
            } else {
              this.fetchList()
              this.$message.success('设置成功')
            }
          }).catch(err => {
            this.$handleNotFound(err, '用户角色不存在')
          })
        })
      },
      // 重置表单验证
      resetForm(formName) {
        // 第一次新增数据时为空对象undefined
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
      }
    },
    created() {
      this.fetchList()
      fetchData({ sources: ['schools'] }).then(res => {
        this.schools = res.schools
      })
    }
  }
</script>

<style  rel="stylesheet/scss" lang="scss" scoped>
    .form-select{
        width: 100%;
    }
    .el-col-6{
        width: 32%;
    }
    .el-icon-check{
        color: green;
    }
    .el-icon-close{
        color: red;
    }
</style>
<style lang="scss">
    .price{
        width: 100px;
        span{
            width: 20px;
        }
        .el-input input{
            padding: 0 20px;
            width: 100px;
        }
    }

</style>
